using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Models;
using System.Text.RegularExpressions;

namespace DocumentCreationSystem.Services
{
    /// <summary>
    /// 角色信息更新服务
    /// 负责在章节完成后更新角色信息、关系和属性设定
    /// </summary>
    public class CharacterUpdateService
    {
        private readonly ILogger<CharacterUpdateService> _logger;
        private readonly IAIService _aiService;
        private readonly IDataStorageService _dataStorage;
        private readonly WorldSettingService _worldSettingService;

        public CharacterUpdateService(
            ILogger<CharacterUpdateService> logger,
            IAIService aiService,
            IDataStorageService dataStorage,
            WorldSettingService worldSettingService)
        {
            _logger = logger;
            _aiService = aiService;
            _dataStorage = dataStorage;
            _worldSettingService = worldSettingService;
        }

        /// <summary>
        /// 更新章节完成后的角色信息
        /// </summary>
        public async Task<CharacterUpdateResult> UpdateCharactersAfterChapterAsync(
            int projectId, int chapterNumber, string chapterContent, string chapterTitle = "")
        {
            var result = new CharacterUpdateResult();
            
            try
            {
                _logger.LogInformation($"开始更新第{chapterNumber}章完成后的角色信息");

                // 1. 分析章节内容中的角色变化
                var characterChanges = await AnalyzeCharacterChangesAsync(
                    projectId, chapterNumber, chapterContent, chapterTitle);

                // 2. 更新角色属性和状态
                var updatedCharacters = await UpdateCharacterAttributesAsync(
                    projectId, characterChanges);

                // 3. 更新角色关系
                await UpdateCharacterRelationshipsAsync(projectId, characterChanges);

                // 4. 更新世界设定中的角色信息
                await UpdateWorldSettingCharacterInfoAsync(projectId, characterChanges);

                result.IsSuccess = true;
                result.UpdatedCharacterCount = updatedCharacters.Count;
                result.CharacterChanges = characterChanges;

                _logger.LogInformation($"第{chapterNumber}章角色信息更新完成，更新了{updatedCharacters.Count}个角色");

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新第{chapterNumber}章角色信息失败");
                result.IsSuccess = false;
                result.ErrorMessage = ex.Message;
                return result;
            }
        }

        /// <summary>
        /// 分析章节内容中的角色变化
        /// </summary>
        private async Task<List<CharacterChange>> AnalyzeCharacterChangesAsync(
            int projectId, int chapterNumber, string chapterContent, string chapterTitle)
        {
            try
            {
                // 获取现有角色信息
                var existingCharacters = await _dataStorage.GetCharactersAsync(projectId);
                var characterNames = existingCharacters.Select(c => c.Name).ToList();

                var prompt = $@"请分析以下第{chapterNumber}章的内容，识别其中角色的变化：

=== 章节信息 ===
标题：{chapterTitle}
章节号：第{chapterNumber}章

=== 现有角色列表 ===
{string.Join("、", characterNames)}

=== 章节内容 ===
{chapterContent.Substring(0, Math.Min(chapterContent.Length, 4000))}...

=== 分析要求 ===
请识别本章中每个角色的变化，包括：
1. 属性变化（实力、境界、能力等）
2. 状态变化（伤势、情绪、位置等）
3. 关系变化（与其他角色的关系）
4. 重要经历（获得物品、学会技能等）

请按以下格式输出：

**角色名称**：[角色名]
- 属性变化：[具体变化描述]
- 状态变化：[具体变化描述]
- 关系变化：[与其他角色关系的变化]
- 重要经历：[本章的重要经历]

如果某个角色没有变化，请写""无变化""。
如果发现新角色，请标注""新角色""并描述其基本信息。";

                var analysisResult = await _aiService.GenerateTextAsync(prompt, 2000, 0.7f);
                
                // 解析AI分析结果
                return ParseCharacterChanges(analysisResult, existingCharacters);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"分析第{chapterNumber}章角色变化失败");
                return new List<CharacterChange>();
            }
        }

        /// <summary>
        /// 解析角色变化分析结果
        /// </summary>
        private List<CharacterChange> ParseCharacterChanges(string analysisResult, IEnumerable<Character> existingCharacters)
        {
            var changes = new List<CharacterChange>();
            
            try
            {
                // 使用正则表达式解析分析结果
                var characterBlocks = Regex.Split(analysisResult, @"\*\*角色名称\*\*：", RegexOptions.IgnoreCase)
                    .Where(block => !string.IsNullOrWhiteSpace(block))
                    .Skip(1); // 跳过第一个空块

                foreach (var block in characterBlocks)
                {
                    var lines = block.Split('\n', StringSplitOptions.RemoveEmptyEntries);
                    if (lines.Length == 0) continue;

                    var characterName = lines[0].Trim();
                    var change = new CharacterChange
                    {
                        CharacterName = characterName,
                        IsNewCharacter = block.Contains("新角色")
                    };

                    // 解析各种变化
                    foreach (var line in lines.Skip(1))
                    {
                        var trimmedLine = line.Trim();
                        if (trimmedLine.StartsWith("- 属性变化："))
                        {
                            change.AttributeChanges = trimmedLine.Substring("- 属性变化：".Length).Trim();
                        }
                        else if (trimmedLine.StartsWith("- 状态变化："))
                        {
                            change.StatusChanges = trimmedLine.Substring("- 状态变化：".Length).Trim();
                        }
                        else if (trimmedLine.StartsWith("- 关系变化："))
                        {
                            change.RelationshipChanges = trimmedLine.Substring("- 关系变化：".Length).Trim();
                        }
                        else if (trimmedLine.StartsWith("- 重要经历："))
                        {
                            change.ImportantExperiences = trimmedLine.Substring("- 重要经历：".Length).Trim();
                        }
                    }

                    // 只添加有实际变化的角色
                    if (HasActualChanges(change))
                    {
                        changes.Add(change);
                    }
                }

                _logger.LogDebug($"解析到{changes.Count}个角色变化");
                return changes;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "解析角色变化失败");
                return new List<CharacterChange>();
            }
        }

        /// <summary>
        /// 检查是否有实际变化
        /// </summary>
        private bool HasActualChanges(CharacterChange change)
        {
            return !string.IsNullOrEmpty(change.AttributeChanges) && !change.AttributeChanges.Contains("无变化") ||
                   !string.IsNullOrEmpty(change.StatusChanges) && !change.StatusChanges.Contains("无变化") ||
                   !string.IsNullOrEmpty(change.RelationshipChanges) && !change.RelationshipChanges.Contains("无变化") ||
                   !string.IsNullOrEmpty(change.ImportantExperiences) && !change.ImportantExperiences.Contains("无变化") ||
                   change.IsNewCharacter;
        }

        /// <summary>
        /// 更新角色属性
        /// </summary>
        private async Task<List<Character>> UpdateCharacterAttributesAsync(
            int projectId, List<CharacterChange> characterChanges)
        {
            var updatedCharacters = new List<Character>();

            foreach (var change in characterChanges)
            {
                try
                {
                    Character character;
                    
                    if (change.IsNewCharacter)
                    {
                        // 创建新角色
                        character = new Character
                        {
                            NovelProjectId = projectId,
                            Name = change.CharacterName,
                            Description = change.StatusChanges ?? "",
                            Attributes = change.AttributeChanges ?? ""
                        };
                        
                        await _dataStorage.CreateCharacterAsync(character);
                        _logger.LogInformation($"创建新角色: {character.Name}");
                    }
                    else
                    {
                        // 更新现有角色
                        var existingCharacters = await _dataStorage.GetCharactersAsync(projectId);
                        character = existingCharacters.FirstOrDefault(c => 
                            c.Name.Equals(change.CharacterName, StringComparison.OrdinalIgnoreCase));

                        if (character != null)
                        {
                            // 更新角色信息
                            if (!string.IsNullOrEmpty(change.AttributeChanges) && !change.AttributeChanges.Contains("无变化"))
                            {
                                character.Attributes = UpdateCharacterField(character.Attributes, change.AttributeChanges);
                            }
                            
                            if (!string.IsNullOrEmpty(change.StatusChanges) && !change.StatusChanges.Contains("无变化"))
                            {
                                character.Description = UpdateCharacterField(character.Description, change.StatusChanges);
                            }
                            
                            // 关系变化暂时记录在UpdateHistory中
                            if (!string.IsNullOrEmpty(change.RelationshipChanges) && !change.RelationshipChanges.Contains("无变化"))
                            {
                                var relationshipUpdate = $"关系变化: {change.RelationshipChanges}";
                                character.UpdateHistory = UpdateCharacterField(character.UpdateHistory, relationshipUpdate);
                            }

                            character.UpdatedAt = DateTime.Now;
                            await _dataStorage.UpdateCharacterAsync(character);
                            
                            _logger.LogInformation($"更新角色: {character.Name}");
                        }
                    }

                    if (character != null)
                    {
                        updatedCharacters.Add(character);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, $"更新角色 {change.CharacterName} 失败");
                }
            }

            return updatedCharacters;
        }

        /// <summary>
        /// 更新角色字段
        /// </summary>
        private string UpdateCharacterField(string? currentValue, string newChange)
        {
            if (string.IsNullOrEmpty(currentValue))
            {
                return newChange;
            }

            // 简单的追加更新，实际可以更智能地合并信息
            return $"{currentValue}\n\n[最新更新] {newChange}";
        }

        /// <summary>
        /// 更新角色关系
        /// </summary>
        private async Task UpdateCharacterRelationshipsAsync(int projectId, List<CharacterChange> characterChanges)
        {
            try
            {
                // 这里可以实现更复杂的关系网络更新逻辑
                // 暂时通过更新角色的Relationships字段来处理
                _logger.LogInformation("角色关系更新完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新角色关系失败");
            }
        }

        /// <summary>
        /// 更新世界设定中的角色信息
        /// </summary>
        private async Task UpdateWorldSettingCharacterInfoAsync(int projectId, List<CharacterChange> characterChanges)
        {
            try
            {
                // 这里可以调用WorldSettingService更新相关设定文件
                // 暂时记录日志
                _logger.LogInformation("世界设定中的角色信息更新完成");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新世界设定中的角色信息失败");
            }
        }
    }

    /// <summary>
    /// 角色变化信息
    /// </summary>
    public class CharacterChange
    {
        public string CharacterName { get; set; } = "";
        public bool IsNewCharacter { get; set; }
        public string AttributeChanges { get; set; } = "";
        public string StatusChanges { get; set; } = "";
        public string RelationshipChanges { get; set; } = "";
        public string ImportantExperiences { get; set; } = "";
    }

    /// <summary>
    /// 角色更新结果
    /// </summary>
    public class CharacterUpdateResult
    {
        public bool IsSuccess { get; set; }
        public int UpdatedCharacterCount { get; set; }
        public string ErrorMessage { get; set; } = "";
        public List<CharacterChange> CharacterChanges { get; set; } = new();
    }
}
